<?php

namespace App\Http\Controllers;

use App\Models\TopicSelection;
use App\Models\ThesisTopic;
use Illuminate\Http\Request;

class TopicSelectionController extends Controller
{
    public function index()
    {
        $selections = TopicSelection::with(['student.user', 'thesisTopic.teacher.user'])->get();
        return response()->json($selections);
    }

    public function store(Request $request)
    {
        $request->validate([
            'topic_id' => 'required|exists:thesis_topics,id',
        ]);

        $topic = ThesisTopic::findOrFail($request->topic_id);
        if ($topic->current_students >= $topic->max_students) {
            return response()->json(['message' => 'This topic has reached its maximum number of students'], 422);
        }

        $selection = TopicSelection::create([
            'student_id' => $request->user()->student->id,
            'topic_id' => $request->topic_id,
        ]);

        return response()->json($selection->load(['student.user', 'thesisTopic.teacher.user']), 201);
    }

    public function show(TopicSelection $selection)
    {
        return response()->json($selection->load(['student.user', 'thesisTopic.teacher.user']));
    }

    public function update(Request $request, TopicSelection $selection)
    {
        $request->validate([
            'status' => 'required|in:approved,rejected',
            'feedback' => 'nullable|string',
        ]);

        $selection->update([
            'status' => $request->status,
            'feedback' => $request->feedback,
            'review_time' => now(),
        ]);

        if ($request->status === 'approved') {
            $selection->thesisTopic->increment('current_students');
        }

        return response()->json($selection->load(['student.user', 'thesisTopic.teacher.user']));
    }

    public function destroy(TopicSelection $selection)
    {
        $selection->delete();
        return response()->json(null, 204);
    }
} 